<?php
/** 
 *  电子合同接口 
 */
namespace tech;
use tech\esign_core\AccountHelper;
use tech\esign_core\InitClientHelper;
use tech\esign_core\SealHelper;
use tech\esign_core\SignHelper;
use tech\esign_utils\CommonHelper;

require_once INCLUDE_ROOT_PATH . 'common.inc.php';
require_once INCLUDE_ROOT_PATH . 'http.class.php';
require_once INCLUDE_ROOT_PATH . 'e_api_v2/eSignOpenAPI.php';

class Econtract_V2
{
    private $init_result = '';

	public function __construct()
	{
        CommonHelper::writeLog('*****初始化SDK，客户短初始化初始化 只需全局初始化一次，初始化成功后，SDK会存储初始化结果，无需重复初始化*****');
        $this->init_result = InitClientHelper::doRegister();
        CommonHelper::writeLog('初始化结果：' . $this->init_result);
	}
    
    /*
    * 创建账户
    * type 账户类型，0-个人，1-企业
    * name 名称、企业名称
    * idcard 创建客户账户：身份证号/护照号，创建企业账户：组织机构代码
    * mobile 手机号
    * $regtype 创建企业账户，企业注册类型，NORMAL（组织机构代码）、MERGE（社会信用代码）、REGCODE（工商注册号），默认NORMAL
    */
    public function addAccount($type, $name, $idcard, $mobile, $regtype='MERGE')
    {   
        $retrun_arr = array('errCode' => 1, 'msg' => '', 'accountid' => 0, 'retinfo' => '');
        $init_result_arr = json_decode($this->init_result, true);
        //判断 初始化e签宝 PHP SDK 是否成功
        if (is_array($init_result_arr) && array_key_exists('errCode', $init_result_arr) && $init_result_arr['errCode'] == 0)
        {
            $acctHelper = new AccountHelper();
            if($type == 0)
            {
                $personAcct = $acctHelper->addPersonAcct($name, $idcard, $mobile, '');
                CommonHelper::writeLog($personAcct);
                if(array_key_exists('errCode', $personAcct) && $personAcct['errCode'] == 0)
                {
                    $retrun_arr['errCode'] = 0;
                    $retrun_arr['accountid'] = $personAcct['accountId'];
                    return $retrun_arr;
                }
                else
                {
                    CommonHelper::writeLog('error:账号创建失败,请填写真实证件号');
                    $retrun_arr['errCode'] = $personAcct['errCode'];
                    $retrun_arr['msg'] = $personAcct['msg'];
                    $retrun_arr['retinfo'] = json_encode($personAcct);
                    return $retrun_arr;
                }
            }
            if($type == 1)
            {
                if (strlen($idcard) == 18){
                    $regtype = 'MERGE';
                }
                $orgAcct = $acctHelper->addOrgAcct($name,$idcard,$regtype,$mobile);
                CommonHelper::writeLog($orgAcct);
                if (array_key_exists('errCode', $orgAcct) && $orgAcct['errCode'] == 0)
                {
                    $retrun_arr['errCode'] = 0;
                    $retrun_arr['accountid'] = $orgAcct['accountId'];
                    return $retrun_arr;
                }
                else
                {
                    CommonHelper::writeLog('error:企业账号创建失败');
                    $retrun_arr['errCode'] = $orgAcct['errCode'];
                    $retrun_arr['msg'] = $orgAcct['msg'];
                    $retrun_arr['retinfo'] = json_encode($orgAcct);
                    return $retrun_arr;
                }
            }
        }
        else
        {
            $retrun_arr['msg'] = '初始化失败!';
            $retrun_arr['retinfo'] = $this->init_result;
        }
        return $retrun_arr;
    }
    
    /*
    * 生成电子印章
    * type 账户类型，0-个人，1-企业
    * accountId 注册的账户id
    * $color （印章颜色，1-红色，2-蓝色，3-黑色）
    * $hText 企业章专用，【横向文字】是用于填写类似“合同专用章”、 “财务专用章”的，如果不需要横向文字则不填写任何字符
    * $qText 企业章专用，【下弦文】是用于填写实体公章中存在的防伪编码（类似“91010086135601”）， 如果不需要下弦文则不填写任何字符
    */    
    public function addTemplateSeal($type, $accountId, $color, $hText='', $qText='', $templateType = 'RECTANGLE')
    {
        $retrun_arr = array('errCode' => 1, 'msg' => '', 'sealData' => 0, 'retinfo' => '');
        $config_sealcolor_arr = array('1' => 'RED', '2' => 'BLUE', '3' => 'BLACK');
        $init_result_arr = json_decode($this->init_result, true);
        //判断 初始化e签宝 PHP SDK 是否成功
        if (is_array($init_result_arr) && array_key_exists('errCode', $init_result_arr) && $init_result_arr['errCode'] == 0)
        {
            if (!array_key_exists($color, $config_sealcolor_arr))
            {
                CommonHelper::writeLog('error:签章颜色参数异常！');
                $retrun_arr['msg'] = '签章颜色参数异常！';
                return $retrun_arr;
            }
            $color_str = $config_sealcolor_arr[$color];
            $sealHelper = new SealHelper();
            if($type == 0)
            {
                CommonHelper::writeLog('*****创建个人模板印章*****');
                $sealInfo = $sealHelper->addPersonSeal($accountId,$color_str,$templateType); //客户印章，SQUARE（正方形），RECTANGLE（长方形）
                CommonHelper::writeLog($sealInfo);
                if (array_key_exists('errCode', $sealInfo) && $sealInfo['errCode'] == 0)
                {
                    $retrun_arr['errCode'] = 0;
                    $retrun_arr['sealData'] = $sealInfo['sealData'];
                    return $retrun_arr;
                }
                else
                {
                    CommonHelper::writeLog('error:生成客户电子印章失败！');
                    $retrun_arr['errCode'] = $sealInfo['errCode'];
                    $retrun_arr['msg'] = '生成客户电子印章失败！';
                    $retrun_arr['retinfo'] = json_encode($sealInfo);
                    return $retrun_arr;
                }
            }
            if($type == 1)
            {
                CommonHelper::writeLog('*****创建企业模板印章*****');
                $sealInfo = $sealHelper->addOrgSeal($accountId,$color_str,'STAR',$hText,$qText); //模板类型，STAR（标准公章），OVAL（椭圆形印章）
                CommonHelper::writeLog($sealInfo);
                if (array_key_exists('errCode', $sealInfo) && $sealInfo['errCode'] == 0)
                {
                    $retrun_arr['errCode'] = 0;
                    $retrun_arr['sealData'] = $sealInfo['sealData'];
                    return $retrun_arr;
                }
                else
                {
                    CommonHelper::writeLog('error:生成公司电子印章失败！');
                    $retrun_arr['errCode'] = $sealInfo['errCode'];
                    $retrun_arr['msg'] = '生成公司电子印章失败！';
                    $retrun_arr['retinfo'] = json_encode($sealInfo);
                    return $retrun_arr;
                }
            }
        }
        else
        {
            $retrun_arr['msg'] = '初始化失败!';
            $retrun_arr['retinfo'] = $this->init_result;
        }
        return $retrun_arr;
    }     
    
    /*
    * 用户签署
    * $accountId 注册的账户id
    * $sealData 电子印章数据
    * $srcPdfFile 原pdf路径/名称
    * $dstPdfFile 签署后pdf路径/名称
    * $signType 1-单页签章，2-多页，3-骑缝，4-关键字;
    * $posPage 签署页码;
    * $posX 签署位置X坐标;
    * $posY 签署位置Y坐标;
    * $key 签署位置关键字;
    */       
    public function userSign($accountId, $sealData, $srcPdfFile, $dstPdfFile, $signType, $posPage, $posX, $posY, $key = '', $width = 180)
    {
        $retrun_arr = array('errCode' => 1, 'msg' => '', 'retinfo' => '');
        //签章类型，Single（单页签章）、Multi（多页签章）、Edges（签骑缝章）、Key（关键字签章）
        $config_seal_arr = array('1' => 'Single', '2' => 'Multi', '3' => 'Edges', '4' => 'Key');
        $init_result_arr = json_decode($this->init_result, true);
        //判断 初始化e签宝 PHP SDK 是否成功
        if (is_array($init_result_arr) && array_key_exists('errCode', $init_result_arr) && $init_result_arr['errCode'] == 0)
        {
            if (!array_key_exists($signType, $config_seal_arr))
            {
                $retrun_arr['msg'] = '请正确填写签章类型!';
                return $retrun_arr;
            }
            CommonHelper::writeLog('*****开始签署*****');
            $signType_str = $config_seal_arr[$signType];
            $signPos = array();
            $signPos['posType'] = $signType == 4 ? 1 : 0;
            $signPos['posPage'] = $posPage;
            $signPos['posX'] = $posX;  //签署位置X坐标,原点为左下角
            $signPos['posY'] = $posY;  //签署位置Y坐标,原点为左下角
            $signPos['width'] = $width; //印章展现宽度
            if ($signType == 4)
            {
                $signPos['key'] = $key;
            }
            $signHelper = new SignHelper();
            $usersignret = $signHelper->userSign($srcPdfFile, $dstPdfFile, $accountId, $sealData, $signPos, $signType_str);
            CommonHelper::writeLog($usersignret);
            if (array_key_exists('errCode', $usersignret) && $usersignret['errCode'] == 0)
            {
                $retrun_arr['errCode'] = 0;
                return $retrun_arr;
            }
            else
            {
                CommonHelper::writeLog('error:生成公司电子印章失败！');
                $retrun_arr['errCode'] = $usersignret['errCode'];
                $retrun_arr['msg'] = '签署失败！';
                $retrun_arr['retinfo'] = json_encode($usersignret);
                return $retrun_arr;
            }
        }
        else
        {
            $retrun_arr['errCode'] = $init_result_arr['errCode'];
            $retrun_arr['msg'] = '初始化失败!';
            $retrun_arr['retinfo'] = $this->init_result;
        }
        return $retrun_arr;
    }

    /**
    *   @todo   根据证件号查询账号信息
    */
    public function getAccountInfoByIdNo($idNo, $idNoType)
    {
        $retrun_arr = array('errCode' => 1, 'msg' => '', 'accountInfo' => '', 'retinfo' => '');
        $init_result_arr = json_decode($this->init_result, true);
        //判断 初始化e签宝 PHP SDK 是否成功
        if (is_array($init_result_arr) && array_key_exists('errCode', $init_result_arr) && $init_result_arr['errCode'] == 0)
        {
            $acctHelper = new AccountHelper();
            $personAcct = $acctHelper->getAccountInfoByIdNo($idNo, $idNoType);
            CommonHelper::writeLog($personAcct);
            if(array_key_exists('errCode', $personAcct) && $personAcct['errCode'] == 0)
            {
                $retrun_arr['errCode'] = 0;
                $retrun_arr['accountInfo'] = $personAcct['accountInfo'];
                return $retrun_arr;
            }
            else
            {
                CommonHelper::writeLog('error:查询账户详情失败！');
                $retrun_arr['errCode'] = $personAcct['errCode'];
                $retrun_arr['msg'] = '查询账户详情失败！' . $personAcct['msg'];
                $retrun_arr['retinfo'] = json_encode($personAcct);
                return $retrun_arr;
            }
        }
        else
        {
            $retrun_arr['errCode'] = $init_result_arr['errCode'];
            $retrun_arr['msg'] = '初始化失败!';
            $retrun_arr['retinfo'] = $this->init_result;
        }
        return $retrun_arr;
    }

    /**
    *   @todo   注销账户，注销后账户将不可再使用，请谨慎调用
    *   param   待注销的accountId
    */
    public function accountDelete($accountId)
    {
        $retrun_arr = array('errCode' => 1, 'msg' => '', 'retinfo' => '');
        $init_result_arr = json_decode($this->init_result, true);
        //判断 初始化e签宝 PHP SDK 是否成功
        if (is_array($init_result_arr) && array_key_exists('errCode', $init_result_arr) && $init_result_arr['errCode'] == 0)
        {
            $acctHelper = new AccountHelper();
            $personAcctDel = $acctHelper->accountDelete($accountId);
            CommonHelper::writeLog($personAcctDel);
            if(array_key_exists('errCode', $personAcctDel) && $personAcctDel['errCode'] == 0)
            {
                $retrun_arr['errCode'] = 0;
                return $retrun_arr;
            }
            else
            {
                CommonHelper::writeLog('error:注销账户失败！');
                $retrun_arr['errCode'] = $personAcctDel['errCode'];
                $retrun_arr['msg'] = '注销账户失败！' . $personAcctDel['msg'];
                $retrun_arr['retinfo'] = json_encode($personAcctDel);
                return $retrun_arr;
            }
        }
        else
        {
            $retrun_arr['errCode'] = $init_result_arr['errCode'];
            $retrun_arr['msg'] = '初始化失败!';
            $retrun_arr['retinfo'] = $this->init_result;
        }
        return $retrun_arr;
    }
}
?>